#!/bin/bash

# ArXiv Subscription Platform Docker Deployment Script

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
COMPOSE_FILE="docker-compose.yml"

# Functions
log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1"
    exit 1
}

info() {
    echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] INFO:${NC} $1"
}

# Check if Docker is installed
check_docker() {
    log "Checking Docker installation..."
    
    if ! command -v docker &> /dev/null; then
        error "Docker is not installed. Please install Docker first."
    fi
    
    if ! docker compose version &> /dev/null; then
        error "Docker Compose is not installed. Please install Docker Compose first."
    fi
    
    log "Docker installation verified"
}

# Create necessary directories
setup_directories() {
    log "Setting up directories..."
    
    mkdir -p logs
    mkdir -p data
    mkdir -p ai_models
    
    log "Directories created"
}

# Build and start services
start_services() {
    log "Building and starting services..."
    
    # Build images
    docker compose build
    
    # Start services
    docker compose up -d
    
    log "Services started"
}

# Wait for services to be ready
wait_for_services() {
    log "Waiting for services to be ready..."
    
    # Wait for PostgreSQL
    info "Waiting for PostgreSQL..."
    while ! docker compose exec postgres pg_isready -U arxiv_user -d arxiv_platform; do
        sleep 2
    done
    
    # Wait for Redis
    info "Waiting for Redis..."
    while ! docker compose exec redis redis-cli ping | grep -q PONG; do
        sleep 2
    done
    
    # Wait for backend API
    info "Waiting for backend API..."
    max_attempts=30
    attempt=1
    while [[ $attempt -le $max_attempts ]]; do
        if curl -f -s http://localhost:8000/health > /dev/null 2>&1; then
            break
        fi
        sleep 2
        ((attempt++))
    done
    
    log "All services are ready"
}

# Show service status
show_status() {
    log "Service Status:"
    echo
    docker compose ps
    echo
    info "Access the application at:"
    info "Frontend: http://localhost:3000"
    info "Backend API: http://localhost:8000"
    info "API Documentation: http://localhost:8000/docs"
    info "Grafana: http://localhost:3001 (admin/admin)"
    info "Prometheus: http://localhost:9090"
    echo
    info "View logs: docker compose logs -f"
    info "Stop services: docker compose down"
    info "Restart services: docker compose restart"
}

# Stop services
stop_services() {
    log "Stopping services..."
    docker compose down
    log "Services stopped"
}

# Clean up
cleanup() {
    log "Cleaning up..."
    docker compose down -v
    docker image prune -f
    log "Cleanup completed"
}

# Main menu
show_menu() {
    echo
    echo "ArXiv Subscription Platform Docker Deployment"
    echo "============================================"
    echo "1. Start services"
    echo "2. Stop services"
    echo "3. Restart services"
    echo "4. View logs"
    echo "5. Clean up (remove volumes)"
    echo "6. Show status"
    echo "7. Exit"
    echo
}

# Main execution
main() {
    check_docker
    setup_directories
    
    while true; do
        show_menu
        read -p "Enter your choice [1-7]: " choice
        
        case $choice in
            1)
                start_services
                wait_for_services
                show_status
                ;;
            2)
                stop_services
                ;;
            3)
                stop_services
                start_services
                wait_for_services
                show_status
                ;;
            4)
                docker compose logs -f
                ;;
            5)
                cleanup
                ;;
            6)
                show_status
                ;;
            7)
                log "Exiting..."
                exit 0
                ;;
            *)
                warn "Invalid choice. Please try again."
                ;;
        esac
    done
}

# Script execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi